import Application from "../application";
import * as define from "../util/define";
import { I_encodeDecodeConfig } from "../util/interfaceDefine";

let app: Application;
export function init(_app: Application) {
  app = _app;
}

export let default_encodeDecode: Required<I_encodeDecodeConfig> = {
  "protoDecode": function (data: Buffer) {
    return {
      "cmd": data.readUInt16BE(1),
      "id": data.readUInt8(3),
      "msg": data.slice(4)
    }
  },
  "msgDecode": function (cmd: number, msg: Buffer) {
    return JSON.parse(msg.toString());
  },
  "protoEncode": function (cmd: number, id: number, msg: any) {
    let msgBuf: Buffer = app.msgEncode(cmd, msg);
    let buf = Buffer.allocUnsafe(msgBuf.length + 8);
    buf.writeUInt32BE(msgBuf.length + 4, 0);
    buf.writeUInt8(define.Server_To_Client.msg, 4);
    buf.writeUInt16BE(cmd, 5);
    buf.writeUInt8(id, 7);
    msgBuf.copy(buf, 8);
    return buf;
  },
  "msgEncode": function (cmd: number, msg: any) {
    return Buffer.from(JSON.stringify(msg));
  }
}
